#include "clientsocket.h"
#include "protocolmessage.h"
#include "zhidebug.h"

ClientSocket::ClientSocket(QObject *parent) : QObject(parent)
{

}

ClientSocket::ClientSocket(const QString host, quint16 port)
{

    tcpSocket = new QTcpSocket(this);
    tcpSocket->connectToHost(host, port);

    connect(tcpSocket, SIGNAL(hostFound()), this, SLOT(slotHostFound()));
    connect(tcpSocket, SIGNAL(connected()), this, SLOT(slotConnected()));
    connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(slotDisconnected()));
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()));
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(slotError(QAbstractSocket::SocketError)));
}

void ClientSocket::sendValidateLoginData(const QString username, const QString password)
{
    if(tcpSocket->state() != QAbstractSocket::ConnectedState){
        ZhiDebug::Error("Failed to connect to server host!");
        return;
    }
    int _length = 0;
    QHash<QString, QString>data;
    data.insert("username", username);
    data.insert("password", password);
    ProtocolMessage *protocolMessage = new ProtocolMessage(ProtocolMessage::VALIDATA, data);
    QString _msg = protocolMessage->toMessage();
    if((_length = tcpSocket->write(_msg.toLatin1())) != _msg.length())
    {
        ZhiDebug::Error("Failed to send message to server!");
    }else{
        ZhiDebug::Info("Success to send message to server!");
    }
}

void ClientSocket::slotError(QAbstractSocket::SocketError)
{
    QString str = tcpSocket->errorString();
    qDebug() <<  str;
    emit receiveData(QString("%1|result|false|message|%2").arg(ProtocolMessage::VALIDATA).arg(str));
}

void ClientSocket::slotHostFound()
{
    ZhiDebug::Info("Found Server Host!");
}

void ClientSocket::slotConnected()
{
    ZhiDebug::Info("Success connect to Server Host!");
    emit connected();
}

void ClientSocket::slotDisconnected()
{
    tcpSocket->close();
    ZhiDebug::Info("Disconnect from Server Host!");
}

void ClientSocket::dataReceived()
{
    QString receviveData = tcpSocket->readAll();
    ZhiDebug::Info("Received data from server! data is \"" + receviveData + "\"");
    emit receiveData(receviveData);
}
